package cn.seqdata.jpa;

import java.util.Comparator;

import org.apache.commons.lang3.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public enum PinYinComparator implements Comparator<String> {
	instance;

	private static final HanyuPinyinOutputFormat fmt = new HanyuPinyinOutputFormat();

	@Override
	public int compare(String o1, String o2) {
		return String.CASE_INSENSITIVE_ORDER.compare(toPinYinString(o1), toPinYinString(o2));
	}

	public static String toPinYinString(String str) {
		if (StringUtils.isBlank(str))
			return str;

		try {
			return PinyinHelper.toHanYuPinyinString(str, fmt, "", true);
		} catch (BadHanyuPinyinOutputFormatCombination ex) {
			return str;
		}
	}
}
